package com.zheng.MyIRule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author lenovo
 */
public class ZhengRule extends AbstractLoadBalancerRule {

    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        }
        Server server = null;

        int total = 0;
        int CurrentIndex = 0;
        while (server == null) {
            if (Thread.interrupted()) {
                return null;
            }
            List<Server> upList = lb.getReachableServers();
            List<Server> allList = lb.getAllServers();

            int serverCount = allList.size();
            int allCount = upList.size();
            if (serverCount == 0) {
                return null;
            }


//            ===============================
            /**
             * 在这里线程显然不安全，我们最好是将它提交到新线程中去执行
             * */
            int index = 0;
            if(total<3){
                index = CurrentIndex;
                total++;
            }else {
                if(index<allCount-1){
                    index = ++CurrentIndex;
                }else {
                    index=0;
                }
                total = 0;
            }
            System.out.println(index);
//            ===============================

            server = upList.get(index);

            if (server == null) {
                Thread.yield();
                continue;
            }

            if (server.isAlive()) {
                return (server);
            }

            server = null;
            Thread.yield();
        }

        return server;

    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    @Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
        // TODO Auto-generated method stub

    }
}
